package com.dbq.fast.fcm;

import android.text.TextUtils;

import com.dbq.fast.App;
import com.dbq.fast.common.bean.User;
import com.dbq.fast.common.net.HttpManager;
import com.dbq.fast.common.net.HttpResult;
import com.dbq.fast.common.net.HttpService;
import com.dbq.fast.util.SpUtil;
import com.google.firebase.iid.FirebaseInstanceId;
import com.yiba.vpn.utils.logger.LogUtil;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Locale;
import java.util.concurrent.Executors;

import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by Widsom Zhang on 2017/11/23.
 */

public class UploadTokenUtil {

    /**
     * 上传firebase message token
     */
    public static void sendFirebaseTokenToServer() {
        String token = FirebaseInstanceId.getInstance().getToken();
        if (TextUtils.isEmpty(token)) {
            token = SpUtil.getString(MyFirebaseInstanceIdService.FIREBASE_MESSAGE_TOKEN);
        }
        if (TextUtils.isEmpty(token)) return;
        String userToken = User.getInstance().getToken();
        String account = User.getInstance().getAccount();
        String country = Locale.getDefault().getCountry();
        if (TextUtils.isEmpty(userToken) || TextUtils.isEmpty(account) || TextUtils.isEmpty(country))
            return;

        HashMap<String, String> body = new HashMap<>();
        body.put("account", account);
        body.put("country", country);
        body.put("token", token);
        Executors.newSingleThreadExecutor().execute(() -> {
            try {
                HttpService httpService = HttpManager.getInstance().getHttpService();
                if (httpService != null) {
                    Call<HttpResult<JSONObject>> call = httpService.uploadFirebaseToken(userToken, body);
                    if (call != null) {
                        Response<HttpResult<JSONObject>> response = call.execute();
                        if (response == null) return;
                        HttpResult result = response.body();
                        if (result == null) return;
                        int code = result.getCode();
                        LogUtil.e("firebase message token code:" + code);
                        if (code == 200) {
                            LogUtil.e("firebase message token upload ok");
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}
